<?php

namespace App\Admin\Forms;

use Dcat\Admin\Models\Administrator;
use Dcat\Admin\Traits\LazyWidget;
use Dcat\Admin\Widgets\Form;
use Dcat\Admin\Contracts\LazyRenderable;
use App\Models\DedustingDevicePoint;
use App\Models\DedustingDevice;
use App\Models\DedustingPointRange;
use Illuminate\Support\Arr;

class SetRanges extends Form implements LazyRenderable
{
    use LazyWidget; // 使用异步加载功能

    // 处理请求
    public function handle(array $input)
    {
        // 获取外部传递参数
        $id = $this->payload['id'] ?? null;
        if (! $id) {
            return $this->response()->error('参数错误');
        }
        $device = DedustingDevice::find($id);
        if (! $device) {
            return $this->response()->error('设备不存在');
        }

        // 表单参数
        $ranges = $input['ranges'] ?? null;

        $device->ranges = json_encode($ranges, JSON_UNESCAPED_UNICODE);
        if ($device->save()) {
            //缓存设置
            DedustingPointRange::setCache($id, $device->ranges);

            return $this->response()->success('设置成功')->refresh();;
        } else {
            return $this->response()->error('设备不存在');
        }
    }

    public function form()
    {
        $this->table('ranges', '点位参考范围', function ($table) {
            $table->hidden('point')->readOnly();
            $table->text('point_text', '点位')->readOnly();
            $table->text('unit', '单位')->required();
            $table->text('min', '最小值')->required();
            $table->text('max', '最大值')->required();
        });

        // 获取外部传递参数
        //$id = $this->payload['id'] ?? null;
    }

    // 返回表单数据，如不需要可以删除此方法
    public function default()
    {

        $id = $this->payload['id'] ?? null;
        $device = DedustingDevice::find($id);
        $ranges = json_decode($device->ranges, true) ?? [];
     
        $default = [];
        foreach (DedustingDevicePoint::POINT_UNITS as $point => $unit) {
            $one['point'] = $point;
            $one['point_text'] = DedustingDevicePoint::POINTS[$point];
            $one['unit'] = $unit;
            $one['min'] = 0;
            $one['max'] = 0;
            array_push($default, $one);
        }
        
        $data = array_merge(Arr::pluck($default, null, 'point'), Arr::pluck($ranges, null, 'point'));   
        return [
            'ranges'         => json_encode($data),
        ];
    }
}